// pages/play/play.js
const api = require('../../api/index')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    musicId:"",
    action:{
      "method":"play"
    },
    showView:false,
    isPlay:false,
    music:{},
    arr:[],
    lyric:[],
    lrcList:[],
    index:-1,
    top:"",
    mode:'loop',
    idlist:[],
    backgroundAudioManager : {}
  },
  show:function(){
    　　this.setData({
         　showView:!this.data.showView
    　　})
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(options.id);
    // console.log(options.idlist);
    var idlistsrc = options.idlist
    var idlist = idlistsrc.split(",")
    // console.log(idlist);
    var mid = options.id
    this.setData({
      musicId:mid,
      idlist:idlist
    })
    const backgroundAudioManager = wx.getBackgroundAudioManager()
    // console.log(backgroundAudioManager);
    this.setData({
      backgroundAudioManager 
    })
  },
  backgroundAudio() {
    let backgroundAudioManager = this.data.backgroundAudioManager
    backgroundAudioManager.title = 'this.data.arr[0].name' 
    backgroundAudioManager.coverImgUrl = ''  // 封面图 URL
    backgroundAudioManager.epname = ''       // 专辑名
    backgroundAudioManager.singer = ''       // 歌手名
    backgroundAudioManager.playbackRate = 1  // 播放速度。范围 0.5-2.0，默认为 1
    backgroundAudioManager.currentTime = 0   // 当前音频的播放位置（单位：s）
    backgroundAudioManager.play()   // 播放音频
    backgroundAudioManager.pause()  // 暂停音频
    backgroundAudioManager.stop()   // 停止播放
    backgroundAudioManager.seek()   // 跳转的位置，单位 s。精确到小数点后 3 位，即支持 ms 级别精确度
    backgroundAudioManager.onPlay(() => {
      // 监听背景音频播放事件
    })
    backgroundAudioManager.onPause(() => {
      // 监听背景音频播放事件
    })
    backgroundAudioManager.onError(() => {
      // 监听背景音频播放错误事件
    })
    backgroundAudioManager.onTimeUpdate(() => {
      // 背景音频播放进度更新事件的监听函数
 
    })
    backgroundAudioManager.onEnded(() => {
      // 监听背景音频自然播放结束事件
    })
    backgroundAudioManager.onNext(() => {
      // 监听用户在系统音乐播放面板点击下一曲事件
    })
    backgroundAudioManager.onPrev(() => {
      // 监听用户在系统音乐播放面板点击上一曲事件
    })
  },
  handlePlay(){
    const isPlay = !this.data.isPlay;
    this.setData({isPlay});
    var date = this.data.action.method
    if (date == "pause") {
      this.setData({
        action:{
          "method":"play"
        }
      })
    }else {
      this.setData({
        action:{
          "method":"pause"
        }
      })
    }
    
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    api.getDetails({ids:this.data.musicId})
    .then(
      content => {
        // console.log(content);
        let {code , songs} = content;
        if (code == 200) {
          this.setData({
            arr : songs
          })
        }
      }
    )
    api.getLyric({id:this.data.musicId})
    .then(
      content => {
        // console.log(content);
        let {code , lrc} = content;
       
        if (code == 200){
          this.setData({
            lyric : lrc
          })
        }
        var lyric = this.data.lyric.lyric
        var lrcstrList = lyric.split("\n")
        var lrctimeList = []
        var re = /\[\d{2}:\d{2}\.\d{2,3}\]/
        for(var i = 0;i < lrcstrList.length;i ++){
          var date = lrcstrList[i].match(re)
          if(date!=null){
            var lrctext = lrcstrList[i].replace(re,"")
            var timest = date[0]
            if(timest!=null){
              var timest_slice = timest.slice(1,-1)
              var splitlist = timest_slice.split(":")
              var f = splitlist[0]
              var m = splitlist[1]
              var time = parseFloat(f)*60 + parseFloat(m)
              lrctimeList.push([time,lrctext])
            }
          }
        }
        this.setData({
          lrcList:lrctimeList
        })
      }
    )
  },
  timechange(result){
    // console.log(result.detail.currentTime);
    var playtime = result.detail.currentTime
    var lrcList = this.data.lrcList
    for(var i = 0;i < lrcList.length-1;i ++){
      if(lrcList[i][0] < playtime && playtime < lrcList[i+1][0]){
        // console.log(lrcList[i][0]);
        this.setData({
          index:i
        })
      }
      var index = this.data.index
      if(index > 5){
        this.setData({
          top:(index - 5)*26
        })
      }
    }
  },

  
  changemode (params){
    if(this.data.mode == 'loop'){
      this.setData({
        mode:'single'
      })
    }else{
      this.setData({
        mode:'loop'
      })
    }
  },

  changeMusic (){
    // console.log("播放完毕");
    var mode = this.data.mode
    if (mode == "single"){
      this.setData({
        musicId:this.data.musicId
      })
      this.setData({
        action:{
          method:"play"
        }
      })
    }else {
      this.nextSong()
    }
  },
  nextSong(){
    var id = this.data.musicId
    var idlist = this.data.idlist
    var index = -1
    var play = this.data.action.method
    var isPlay = this.data.isPlay
    for(var i = 0; i < idlist.length; i ++){
      if(id == idlist[i]){
        index = i
        break
      }
    }
    if(index == idlist.length - 1){
      this.setData({
        id:idlist[0]
      })
    }else {
      this.setData({
        musicId:idlist[index + 1]
      })
      this.setData({
        action:{
          method:"play"
        }
      })
    }
    if(play == "pause"){
      this.setData({
        isPlay: false
      })
    }
    api.getDetails({ids:this.data.musicId})
    .then(
      content => {
        // console.log(content);
        let {code , songs} = content;
        if (code == 200) {
          this.setData({
            arr : songs
          })
        }
      }
    )
    api.getLyric({id:this.data.musicId})
    .then(
      content => {
        // console.log(content);
        let {code , lrc} = content;
       
        if (code == 200){
          this.setData({
            lyric : lrc
          })
        }
        var lyric = this.data.lyric.lyric
        var lrcstrList = lyric.split("\n")
        var lrctimeList = []
        var re = /\[\d{2}:\d{2}\.\d{2,3}\]/
        for(var i = 0;i < lrcstrList.length;i ++){
          var date = lrcstrList[i].match(re)
          if(date!=null){
            var lrctext = lrcstrList[i].replace(re,"")
            var timest = date[0]
            if(timest!=null){
              var timest_slice = timest.slice(1,-1)
              var splitlist = timest_slice.split(":")
              var f = splitlist[0]
              var m = splitlist[1]
              var time = parseFloat(f)*60 + parseFloat(m)
              lrctimeList.push([time,lrctext])
            }
          }
        }
        this.setData({
          lrcList:lrctimeList
        })
      }
    )
    
  },

  prevSong(){
    var id = this.data.musicId
    var idlist = this.data.idlist
    var index = -1
    var play = this.data.action.method
    var isPlay = this.data.isPlay
    for(var i = 0; i < idlist.length; i ++){
      if(id == idlist[i]){
        index = i
        break
      }
    }
    if(index == 0){
      this.setData({
        id:idlist[idlist.length - 1]
      })
    }else {
      this.setData({
        musicId:idlist[index - 1]
      })
      this.setData({
        action:{
          method:"play"
        }
      })
    }
    if(play == "pause"){
      this.setData({
        isPlay: false
      })
    }
    api.getDetails({ids:this.data.musicId})
    .then(
      content => {
        // console.log(content);
        let {code , songs} = content;
        if (code == 200) {
          this.setData({
            arr : songs
          })
        }
      }
    )
    api.getLyric({id:this.data.musicId})
    .then(
      content => {
        // console.log(content);
        let {code , lrc} = content;
       
        if (code == 200){
          this.setData({
            lyric : lrc
          })
        }
        var lyric = this.data.lyric.lyric
        var lrcstrList = lyric.split("\n")
        var lrctimeList = []
        var re = /\[\d{2}:\d{2}\.\d{2,3}\]/
        for(var i = 0;i < lrcstrList.length;i ++){
          var date = lrcstrList[i].match(re)
          if(date!=null){
            var lrctext = lrcstrList[i].replace(re,"")
            var timest = date[0]
            if(timest!=null){
              var timest_slice = timest.slice(1,-1)
              var splitlist = timest_slice.split(":")
              var f = splitlist[0]
              var m = splitlist[1]
              var time = parseFloat(f)*60 + parseFloat(m)
              lrctimeList.push([time,lrctext])
            }
          }
        }
        this.setData({
          lrcList:lrctimeList
        })
      }
    )
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})